<template>
  <div class="history">
    <div class="earnings-summary">
      <div class="total-earnings">
        <h2>总收入</h2>
        <p class="amount">¥ {{ formatAmount(totalAmount) }}</p>
      </div>
      <div class="order-stats">
        <div class="stat">
          <span class="label">总单数</span>
          <span class="value">{{ totalSize }}单</span>
        </div>
        <div class="stat">
          <span class="label">今日收入</span>
          <span class="value">¥ {{ formatAmount(dailyTotalAmount) }}</span>
        </div>
        <div class="stat">
          <span class="label">今日单数</span>
          <span class="value">{{ dailyTotalSize }}单</span>
        </div>
      </div>
    </div>

    <div class="order-history">
      <h2>订单记录</h2>
      <van-list>
        <van-cell-group>
          <van-cell v-for="(order, index) in orders" :key="index" class="order-item">
            <div class="order-header">
              <span class="order-time">{{ order.data_time }}</span>
              <span class="order-price">¥ {{ extractPrice(order.details) }}</span>
            </div>
            <div class="order-details">
              <div class="order-passengers">
                <van-icon name="friends-o" />
                <span>{{ extractPassengers(order.details) }}</span>
              </div>
              <div class="order-distance">
                <van-icon name="location-o" />
                <span>{{ extractDistance(order.details) }}</span>
              </div>
            </div>
            <div class="order-route">
              <div class="route-start">
                <van-icon name="arrow-up" />
                <span>{{ order.from_name }}</span>
              </div>
              <div class="route-end">
                <van-icon name="arrow-down" />
                <span>{{ order.to_name }}</span>
              </div>
            </div>
            <div class="order-time-info">
              <van-icon name="clock-o" />
              <span>{{ order.start_time }}</span>
            </div>
          </van-cell>
        </van-cell-group>
      </van-list>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, computed } from 'vue';
import { useStore } from 'vuex';
import { showNotify } from 'vant';
import { StorageUtil } from '@/utils/storage'
import { orderApi } from '@/api'
import qs from 'qs'

export default {
  name: 'HistoryView',
  setup() {
    const store = useStore();
    const active = computed(() => store.state.active)

    watch(active, (newValue) => {
      if (newValue === '2') {
        fetchHistoryOrders()
      }
    })


    const orders = ref([])
    const totalAmount = ref(0)
    const totalSize = ref(0)
    const dailyTotalAmount = ref(0)
    const dailyTotalSize = ref(0)

    const fetchHistoryOrders = async () => {
      try {
        const params = qs.stringify({
          cardKey: StorageUtil.getCardKey()
        });
        const response = await orderApi.queryOrderSuccessList(params);

        // 直接使用返回的值
        totalAmount.value = response.total_amount
        totalSize.value = response.total_size
        dailyTotalAmount.value = response.daily_total_amount
        dailyTotalSize.value = response.daily_total_size

        orders.value = response.dataList;
      } catch (error) {
        console.log(error);
        showNotify({
          type: 'danger',
          message: '获取历史订单失败'
        });
      }
    }

    // 辅助方法：提取价格
    const extractPrice = (details) => {
      const priceMatch = details.match(/(\d+\.\d+)元/)
      return priceMatch ? priceMatch[1] : '0'
    }

    // 辅助方法：提取乘客数
    const extractPassengers = (details) => {
      const passengersMatch = details.match(/(\d+)人(独享|愿拼)/)
      return passengersMatch ? `${passengersMatch[1]}人${passengersMatch[2]}` : '未知'
    }

    // 辅助方法：提取里程
    const extractDistance = (details) => {
      const distanceMatch = details.match(/订单里程([\d.]+)km/)
      return distanceMatch ? `${distanceMatch[1]}km` : '未知'
    }

    // 判断是否为今天的订单
    const isToday = (dateString) => {
      const orderDate = new Date(dateString)
      const today = new Date()
      return orderDate.getFullYear() === today.getFullYear() &&
        orderDate.getMonth() === today.getMonth() &&
        orderDate.getDate() === today.getDate()
    }

    // 格式化金额
    const formatAmount = (amount) => {
      return amount.toFixed(2)
    }

    onMounted(() => {
      fetchHistoryOrders()
    })

    return {
      orders,
      totalAmount,
      totalSize,
      dailyTotalAmount,
      dailyTotalSize,
      extractPrice,
      extractPassengers,
      extractDistance,
      formatAmount
    }
  }
}
</script>

<style scoped>
.history {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.earnings-summary {
  background-color: white;
  padding: 20px;
  margin-bottom: 10px;
}

.total-earnings {
  text-align: center;
  margin-bottom: 20px;
}

.total-earnings h2 {
  color: #666;
  margin-bottom: 10px;
}

.total-earnings .amount {
  font-size: 24px;
  font-weight: bold;
  color: #ff4444;
}

.order-stats {
  display: flex;
  justify-content: space-between;
}

.stat {
  text-align: center;
  flex: 1;
}

.stat .label {
  color: #666;
  display: block;
  margin-bottom: 5px;
}

.stat .value {
  font-weight: bold;
  color: #333;
}

.order-history {
  background-color: white;
  padding: 20px;
}

.order-history h2 {
  margin-bottom: 15px;
  color: #333;
}

.order-item {
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.order-time {
  color: #666;
}

.order-price {
  color: #ff4444;
  font-weight: bold;
}

.order-details {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.order-route {
  margin-bottom: 10px;
}

.route-start,
.route-end {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.route-start van-icon,
.route-end van-icon {
  margin-right: 10px;
}

.order-time-info {
  display: flex;
  align-items: center;
  color: #666;
}

.order-time-info van-icon {
  margin-right: 10px;
}
</style>
